package com.jb.workflow.app.ui;

import java.util.List;

import net.oschina.app.AppConfig;
import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.bean.Notice;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.ui.BaseActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.jb.workflow.app.bean.ProcessInst;
import com.jb.workflow.app.client.StepDescriptor;
import com.jb.workflow.app.client.WfUtil;

public class InstDetail extends BaseActivity {
	
	public final static String TAG = "InstDetail";
	
	private FrameLayout mHeader;
	private LinearLayout mFooter;
	private ImageView mBack;
	private ImageView mRefresh;
	private TextView mHeadTitle;
	private ProgressBar mProgressbar;
	private ScrollView mScrollView;
	
	private TextView mProcessDetail;
	private TextView mTitle;
	private TextView mAuthor;
	private TextView mPubDate;
	private TextView mCommentCount;
	
	private WebView mWebView;
    private Handler mHandler;
    
    private ProcessInst inst;
    
    private int instId;
    private String instCustomer;
    private String instComment;
    private String instOrderId;
    private String instDate;
    private String instStep;
    private String instAuthor;
    //claim or 
    private String action;
    
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	private final static int DATA_LOAD_FAIL = 0x003;
	
    //private int curId;
    private String _content;
    //private String _account;
    
    //private EditText mFootEditer;
	//private Button mFootComplete;	
	//private ProgressDialog mProgress;
	private InputMethodManager imm;
	//private String tempInstNoticeKey;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inst_detail);
        
        this.initView();        
        this.initData();
    }
    
    //****增加其他类型任务的显示支持，可能不是客户，订单号等流程变量
    // 隐藏输入发表回帖状态
    private void hideEditor(View v) {
    	imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
    
    //初始化视图控件
    private void initView()
    {
    	inst = (ProcessInst)getIntent().getSerializableExtra("inst");
    	
    	if (inst == null) {
    		return;
    	}
    	
    	//tempInstNoticeKey = AppConfig.TEMP_TODO_NOTICE + "_" + 1 + "_" + inst.getId();
    	
    	mHeader = (FrameLayout)findViewById(R.id.inst_detail_header);
    	mFooter = (LinearLayout)findViewById(R.id.inst_detail_footer);
    	mBack = (ImageView)findViewById(R.id.inst_detail_back);
    	mRefresh = (ImageView)findViewById(R.id.inst_detail_refresh);
    	mProgressbar = (ProgressBar)findViewById(R.id.inst_detail_head_progress);
    	mHeadTitle = (TextView)findViewById(R.id.inst_detail_head_title);
    	//mViewSwitcher = (ViewSwitcher)findViewById(R.id.inst_detail_viewswitcher);
    	mScrollView = (ScrollView)findViewById(R.id.inst_detail_scrollview);
    	
    	//mDetail = (ImageView)findViewById(R.id.inst_detail_footbar_detail);
    	//mCommentList = (ImageView)findViewById(R.id.inst_detail_footbar_commentlist);
    	//mShare = (ImageView)findViewById(R.id.inst_detail_footbar_share);
    	//mFavorite = (ImageView)findViewById(R.id.inst_detail_footbar_favorite);
    	
    	//mDocTYpe = (ImageView)findViewById(R.id.inst_detail_documentType);
    	mProcessDetail = (TextView)findViewById(R.id.inst_detail_step);
    	mTitle = (TextView)findViewById(R.id.inst_detail_title);
    	mAuthor = (TextView)findViewById(R.id.inst_detail_author);
    	mPubDate = (TextView)findViewById(R.id.inst_detail_date);
    	mCommentCount = (TextView)findViewById(R.id.inst_detail_commentcount);
    	
    	//mDetail.setEnabled(false);
    	
    	mWebView = (WebView)findViewById(R.id.inst_detail_webview);
    	mWebView.getSettings().setSupportZoom(true);
    	mWebView.getSettings().setBuiltInZoomControls(true);
    	mWebView.getSettings().setDefaultFontSize(15);
    	//UIHelper.addWebImageShow(this, mWebView);
    	
    	mBack.setOnClickListener(UIHelper.finish(this));
    	//mFavorite.setOnClickListener(favoriteClickListener);
    	mRefresh.setOnClickListener(refreshClickListener);
    	//mAuthor.setOnClickListener(authorClickListener);
    	//mShare.setOnClickListener(shareClickListener);
    	//mDetail.setOnClickListener(detailClickListener);
    	//mCommentList.setOnClickListener(commentlistClickListener);
    	
//    	bv_comment = new BadgeView(this, mCommentList);
//    	bv_comment.setBackgroundResource(R.drawable.widget_count_bg2);
//    	bv_comment.setIncludeFontPadding(false);
//    	bv_comment.setGravity(Gravity.CENTER);
//    	bv_comment.setTextSize(8f);
//    	bv_comment.setTextColor(Color.WHITE);
    	
    	imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	
    	//mFootViewSwitcher = (ViewSwitcher)findViewById(R.id.inst_detail_foot_viewswitcher);
    	//mFootComplete = (Button)findViewById(R.id.inst_detail_foot_complete);
    	//mFootComplete.setOnClickListener(submitClickListener);
//    	mFootEditebox = (ImageView)findViewById(R.id.inst_detail_footbar_editebox);
//    	mFootEditebox.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View v) {
//				mFootViewSwitcher.showNext();
//				mFootEditer.setVisibility(View.VISIBLE);
//				mFootEditer.requestFocus();
//				mFootEditer.requestFocusFromTouch();
//			}
//		});
//    	mFootEditer = (EditText)findViewById(R.id.inst_detail_foot_editer);
//    	mFootEditer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//			public void onFocusChange(View v, boolean hasFocus) {
//				if(hasFocus){  
//					imm.showSoftInput(v, 0);  
//		        }  
//		        else {  
//		            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//		            hideEditor(v);
//		        }  
//			}
//		}); 
//    	mFootEditer.setOnKeyListener(new View.OnKeyListener() {
//			public boolean onKey(View v, int keyCode, KeyEvent event) {
//				if (keyCode == KeyEvent.KEYCODE_BACK) {
//					hideEditor(v);
//					return true;
//				}
//				return false;
//			}
//		});
    	// 编辑器添加文本监听
    	//mFootEditer.addTextChangedListener(UIHelper.getTextWatcher(this, tempInstNoticeKey));
    	
    	// 显示临时编辑内容
    	//UIHelper.showTempEditContent(this, mFootEditer, tempInstNoticeKey);
    	
    	if (inst.getCompleted()) {//已经完成的实例
    		
    	} else {//正在运行的实例
    		
    	}
    	mFooter.setVisibility(View.GONE);
    }
    
    //初始化控件数据
	private void initData()
	{	
		mHandler = new Handler()
		{
			public void handleMessage(Message msg) 
			{				
				if(msg.what == 1)
				{					
					headButtonSwitch(DATA_LOAD_COMPLETE);
					List<String> comments = inst.getCompleteTime();
					StepDescriptor despGetter = new StepDescriptor(inst.getNeedDriver());
					
					String step = null;
					if (inst.getCompleted()) {
						step = "结束于" + StringUtils.friendly_timewf(inst.getEndDate());
					} else {
						step = despGetter.getCurrStepDesp(comments.size());
					}
					
					String title = inst.getCustomer() + ": 订单号" + inst.getOrderId();
					if (!inst.getNeedDriver()) {
						title += "<不需发货>";
					}

					mTitle.setText(title);
					mAuthor.setText(inst.getStartUserId());
					mPubDate.setText(StringUtils.friendly_timewf(inst.getStartDate()));
					mCommentCount.setText(step);
					
					StringBuilder process = new StringBuilder();
					process.append(StringUtils.showDetailTimewf(inst.getStartDate()));
					process.append("\t订单创建");

					//索引需要小于当前任务类型的任务完成的步骤数量
					//第一条是下单完成的记录，从第二条开始是库房接单提货的完成
					for (int i = 0; i < comments.size() && i < despGetter.getFinishedStepCount(); i++) {
						process.append("\r\n");
						process.append(StringUtils.showDetailTimewf(comments.get(i)));
						process.append("\t");
						process.append(despGetter.getStepEndDesp(i));
						process.append("已完成");
					}
					if (inst.getCompleted()) {
						process.append("\r\n");
						process.append(StringUtils.showDetailTimewf(inst.getEndDate()));
						process.append("\t");
						if (despGetter.isFinished(comments.size())) {
							process.append("成功结束");
						} else {
							process.append("异常结束");
						}
					}
					
					mProcessDetail.setText(process);
					
					mWebView.loadDataWithBaseURL(null, inst.getComment(), "text/plain", "utf-8", null);
					//mWebView.setWebViewClient(UIHelper.getWebViewClient());
					
					//发送通知广播
					if(msg.obj != null) {
						UIHelper.sendBroadCast(InstDetail.this, (Notice)msg.obj);
					}
				}
				else if(msg.what == 0)
				{
					headButtonSwitch(DATA_LOAD_FAIL);
					
					UIHelper.ToastMessage(InstDetail.this, R.string.msg_load_is_null);
				}
				else if(msg.what == -1 && msg.obj != null)
				{
					headButtonSwitch(DATA_LOAD_FAIL);
					
					((AppException)msg.obj).makeToast(InstDetail.this);
				}
			}
		};
		
		initData(instId, false);
	}
	
    private void initData(final int instId, final boolean isRefresh)
    {	
    	headButtonSwitch(DATA_LOAD_ING);
    	
		new Thread() {
			public void run() {
                Message msg = new Message();
				try {//****得到任务的详细信息
					((AppContext)getApplication()).setOrderInstDetail(inst);
					
					msg.what = 1;
	                msg.what = inst.isHasDetail() ? 1 : 0;
	            } catch (Exception e) {
	                e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
                mHandler.sendMessage(msg);
			}
		}.start();
    }
    
    private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			hideEditor(v);
			initData(instId, true);
			//loadLvCommentData(curId,0,mCommentHandler,UIHelper.LISTVIEW_ACTION_REFRESH);
		}
	};
	
    
    /**
     * 头部按钮展示
     * @param type
     */
    private void headButtonSwitch(int type) {
    	switch (type) {
		case DATA_LOAD_ING:
			mScrollView.setVisibility(View.GONE);
			mProgressbar.setVisibility(View.VISIBLE);
			mRefresh.setVisibility(View.GONE);
			break;
		case DATA_LOAD_COMPLETE:
			mScrollView.setVisibility(View.VISIBLE);
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		case DATA_LOAD_FAIL:
			mScrollView.setVisibility(View.GONE);
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		}
    }
}
